package com.treeroot.servicebase.config;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
/**
 * @Description:
 * @Author:treeRoot
 * @Email:553503639@qq.com
 * @Date: Create in 12:46 / 2022/6/25
 */

public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    private double apiVersion = 1.0;

    private static final String VERSION_NAME = "api-version";

    public double getApiVersion() {
        return apiVersion;
    }

    public ApiVersionRequestCondition(double apiVersion){
        this.apiVersion=apiVersion;
    }

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition method) {
        return method;
    }

    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
        return Double.compare(other.getApiVersion(),this.getApiVersion());
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {

        double reqVersionDouble = 1.0;

        String reqVersion = request.getHeader(VERSION_NAME);
        if(StringUtils.isEmpty(reqVersion)){
            reqVersion = request.getParameter(VERSION_NAME);
        }

        if(!StringUtils.isEmpty(reqVersion)){
            reqVersionDouble = Double.parseDouble(reqVersion);
        }

        if(this.getApiVersion() == reqVersionDouble){
            return this;
        }
        return null;
    }
}